package com.seari.groovyrunner.controller;

import com.seari.groovyrunner.bean.GroovyLogInterfacce;
import com.seari.groovyrunner.bean.GroovyTask;
import com.seari.groovyrunner.bean.ReturnBean;
import com.seari.groovyrunner.main.StartUpClass;
import com.seari.groovyrunner.utils.GrooyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "")
public class MappingController {

    @RequestMapping(value = "/home")
    public String home() {
        return "home";
    }

    @RequestMapping(value = "/codeEditer")
    public String codeEditer() {
        return "codeEditer";
    }

    @RequestMapping(value = "/addScript")
    public String addScript() {
        return "addScript";
    }

    @RequestMapping(value = "/uploadScript")
    public String uploadScript() {
        return "uploadScript";
    }

    @RequestMapping(value = "/addService")
    public String addService() {
        return "addService";
    }

    @RequestMapping(value = "/logPage")
    public String logPage() {
        return "logPage";
    }

    @RequestMapping(value = "/groovyDynamic/{path}")
    @ResponseBody
    @GroovyLogInterfacce(logModul = "Groovy脚本-接口访问模块",logType = "groovyDynamicAdd",logDesc = "请求接口访问")
    public ReturnBean echo(@PathVariable("path") String path, HttpServletRequest req){
        ReturnBean bean=new ReturnBean();
        if (path!=null&&path.length()>0){
            GroovyTask groovyTask = StartUpClass.serviceMapping.get(path);
            if (groovyTask!=null){
                try {
                    Object execute = GrooyUtils.execute(groovyTask.getGpath(), groovyTask.getGmethod(), req);
                    bean.setCode(200);
                    bean.setMsg("执行成功");
                    bean.setData(execute);
                } catch (Exception e) {
                    bean.setCode(400);
                    bean.setMsg("脚本异常");
                    bean.setData(e.getMessage());
                }
            }else{
                bean.setCode(500);
                bean.setMsg("当前路径没有运行中接口");
            }
        }else{
            bean.setCode(500);
            bean.setMsg("路径不能为null");
        }
        return bean;
    }
}